package com.cust.zy.newtask.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.cust.zy.newtask.tools.TaskResult;
import com.cust.zy.newtask.R;
import com.cust.zy.newtask.TaskApplication;
import com.cust.zy.newtask.dao.DataOperation;
import com.cust.zy.newtask.model.Task;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhuangyuan on 4/12/2017.
 * 邮箱：zhuangyuan.k@qq.com
 */
public class TaskListActivity extends AppCompatActivity {

    private final static String LOG = "TaskListActivity";
    public final static String SELECTED_TASK = "SELECTED_TASK";
    private DataOperation dataOperation;
    private int exitApplicationCertain = 0;
    private ListView taskList;

    ArrayList<Task> taskData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_list);
        dataOperation = new DataOperation(this);
        final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //app logo
        toolbar.setLogo(R.mipmap.ic_launcher);
        toolbar.setTitle("任务列表");
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setRippleColor(getResources().getColor(android.R.color.holo_orange_light));
        fab.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(android.R.color.holo_green_light)));
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(TaskListActivity.this, NewTaskActivity.class);
                startActivity(intent);
            }
        });
        taskList = (ListView) this.findViewById(R.id.planList);
        GetTaskListTask getTaskListTask = new GetTaskListTask();
        getTaskListTask.execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        else if(id == R.id.action_add){
            Intent intent = new Intent(TaskListActivity.this, NewTaskActivity.class);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }

    private class GetTaskListTask extends AsyncTask<String, Object, TaskResult<ArrayList<Task>>> {
        private Task task;
        @Override
        protected TaskResult<ArrayList<Task>> doInBackground(String... arg0) {
            try{
                taskData = dataOperation.queryTask(null,null);
                Log.e(LOG,taskData.toArray().toString());
                return new TaskResult<>(taskData);
            }
            catch(Exception e){
                return new TaskResult<>(e);
            }
        }
        @Override
        protected void onPostExecute(TaskResult<ArrayList<Task>> result) {
            if(result.isValid()){
                List<Task> list = result.getResult();
                List<Map<String, Object>> taskListData = new ArrayList<Map<String, Object>>();
                for (int i = 0; i < list.size(); i++) {
                    Task task = list.get(i);
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("name",task.getName());
                    map.put("process", "2/10");
                    map.put("startTime", task.getGenerateTime());
                    map.put("description", task.getDescription());
                    map.put("index",i);
                    taskListData.add(map);
                }
                SimpleAdapter adapter = new SimpleAdapter(
                        TaskListActivity.this, taskListData, R.layout.item_task_list,
                        new String[]{"name", "process", "startTime", "description"},
                        new int[]{R.id.plan_name, R.id.plan_process,
                                R.id.plan_startTime, R.id.plan_description});
                taskList.setAdapter(adapter);
                taskList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        ListView listview = (ListView) parent;
                        Map<String,Object> map = (Map<String,Object>)
                                listview.getItemAtPosition(position);
                        int index = (int) map.get("index");
                        Task selectedTask  = taskData.get(index);
                        TaskApplication application = (TaskApplication)getApplication();

                        if(selectedTask.getID().equals(application.getTask().getID())){
                            Intent intent = new Intent(TaskListActivity.this, TaskActivity.class);
                            startActivity(intent);
                        }
                        else application.initialData(selectedTask.getID());

                        SharedPreferences preferences = getApplication()
                                .getSharedPreferences("preferences", MODE_PRIVATE);
                        SharedPreferences.Editor edit = preferences.edit();
                        edit.putString("TaskID", selectedTask.getID());
                        edit.commit();
                        finish();
                    }
                });
                taskList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                    @Override
                    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                        ListView list = (ListView)parent;
                        Map<String, Object> map = (Map<String, Object>)
                                list.getItemAtPosition(position);
                        int index = (int) map.get("index");
                        final Task selectedTask  = taskData.get(index);
                        String[] items = {"修改","删除","详情"};
                        AlertDialog.Builder builder =
                                new AlertDialog.Builder(TaskListActivity.this);
                        builder.setTitle("操作列表");
                        builder.setItems(items, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch(which){
                                    case 0:
                                        Intent intent = new Intent(TaskListActivity.this,
                                                AlterTaskActivity.class);
                                        intent.putExtra(SELECTED_TASK,selectedTask);
                                        startActivity(intent);
                                        break;
                                    case 1:
                                        DeleteTaskTask deleteTaskTask =
                                                new DeleteTaskTask(selectedTask.getID());
                                        deleteTaskTask.execute();
                                        break;
                                }
                            }
                        });
                        builder.show();
                        return true;
                    }
                });
            }
            else{
                result.getException().printStackTrace();
                Log.e(LOG,result.getException().toString());
            }
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(exitApplicationCertain==0){
                Toast.makeText(TaskListActivity.this,"再一次点击退出应用程序",Toast.LENGTH_SHORT).show();
                exitApplicationCertain++;
            }else{
                Intent intent = new Intent(Intent.ACTION_MAIN);
                startActivity(intent);
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        }
        return false;
    }
    private class DeleteTaskTask extends AsyncTask<String, Object, TaskResult<Boolean>> {
        private String taskID;

        public DeleteTaskTask(String taskID) {
            this.taskID = taskID;
        }
        @Override
        protected TaskResult<Boolean> doInBackground(String... arg0) {
            try {
                dataOperation.deleteTask(taskID);
                return new TaskResult<Boolean>(true);
            } catch (Exception e) {
                return new TaskResult<Boolean>(e);
            }
        }

        @Override
        protected void onPostExecute(TaskResult<Boolean> result) {
            if(result.isValid()){
                GetTaskListTask getTaskListTask = new GetTaskListTask();
                getTaskListTask.execute();
            }
        }
    }
}
